<template>
	<view>
		<view style="padding: 15px;">
			<up-form class="apply-form-field" ref="userForm" :model="form" labelPosition="left" :labelStyle="labelStyle"
				:borderBottom="true">
				<!-- #ifdef APP -->
				<up-form-item label="申请日期" label-width="120" prop="createDate" required :borderBottom="true"
					@tap="createDateShow = true">
					<up-input placeholder="请选择申请日期" type="text" class="form-field-select" v-model="form.createDate"
						border="none" readonly />
				</up-form-item>
				<up-form-item label="部门" label-width="120" prop="departmentName" required :borderBottom="true"
					@tap="departmentShow = true">
					<up-input placeholder="请选择部门" type="text" class="form-field-select" v-model="form.departmentName"
						border="none" readonly />
				</up-form-item>
				<up-form-item label="销售人员" label-width="120" prop="salePerson" required :borderBottom="true"
					@tap="salePersonShow = true">
					<up-input placeholder="请选择销售人员" type="text" class="form-field-select" v-model="form.salePerson"
						border="none" readonly />
				</up-form-item>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<up-form-item label="申请日期" label-width="120" prop="createDate" required :borderBottom="true">
					<up-input placeholder="请选择申请日期" type="text" class="form-field-select" v-model="form.createDate"
						border="none" @click.native="createDateShow=true" @focus='blur' />
				</up-form-item>
				<up-form-item label="部门" label-width="120" prop="departmentName" required :borderBottom="true">
					<up-input placeholder="请选择部门" type="text" class="form-field-select" v-model="form.departmentName"
						border="none" @click.native="departmentShow=true" @focus='blur' />
				</up-form-item>
				<up-form-item label="销售人员" label-width="120" prop="salePerson" required :borderBottom="true">
					<up-input placeholder="请选择销售人员" type="text" class="form-field-select" v-model="form.salePerson"
						border="none" @click.native="salePersonShow=true" @focus='blur' />
				</up-form-item>
				<!-- #endif -->
				<up-form-item label="客户姓名" label-width="120" prop="customerName" required :borderBottom="true">
					<up-input placeholder="请输入客户姓名" type="text" class="form-field-select" v-model="form.customerName"
						border="none" />
				</up-form-item>
				<up-form-item label="客户编号" label-width="120" prop="customerNo" :borderBottom="true">
					<up-input placeholder="自动生成" type="text" class="form-field-select" v-model="form.customerNo"
						border="none" readonly disabled />
				</up-form-item>
				<up-form-item label="客户等级" label-width="120" prop="customerLevel" :borderBottom="true">
					<up-input placeholder="请输入客户等级" type="text" class="form-field-select" v-model="form.customerLevel"
						border="none" />
				</up-form-item>
				<!-- #ifdef APP -->
				<up-form-item label="客户形式" label-width="120" prop="customerForm" required :borderBottom="true"
					@tap="formShow = true">
					<up-input placeholder="请选择客户形式" type="text" class="form-field-select" v-model="form.customerForm"
						border="none" readonly />
				</up-form-item>
				<up-form-item label="所在区域" label-width="120" prop="department" required :borderBottom="true"
					@tap="areListShow = true">
					<up-input placeholder="请选择客户所在区域" type="text" class="form-field-select" v-model="form.department"
						border="none" readonly />
				</up-form-item>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<up-form-item label="客户形式" label-width="120" prop="customerForm" required :borderBottom="true">
					<up-input placeholder="请选择客户形式" type="text" class="form-field-select" v-model="form.customerForm"
						border="none" @click.native="formShow=true" @focus='blur' />
				</up-form-item>
				<up-form-item label="所在区域" label-width="120" prop="department" required :borderBottom="true">
					<up-input placeholder="请选择客户所在区域" type="text" class="form-field-select" v-model="form.department"
						border="none" @click.native="areListShow=true" @focus='blur' />
				</up-form-item>
				<!-- #endif -->
				<up-form-item label="付款账期" label-width="120" prop="accountPeriod" required :borderBottom="true">
					<up-radio-group v-model="form.accountPeriod" shape="square">
						<up-radio v-for="(item, index) in accountPeriodList" :key="index" :name="item" :label="item"
							activeColor="green"></up-radio>
					</up-radio-group>
				</up-form-item>
				<up-form-item label="收货人" label-width="120" prop="customerTake" required :borderBottom="true">
					<up-input placeholder="请输入收货人" type="text" class="form-field-select" v-model="form.customerTake"
						border="none" />
				</up-form-item>
				<up-form-item label="收货人电话" label-width="120" prop="customerPhone" required :borderBottom="true">
					<up-input type="number" placeholder="请输入收货人电话" class="form-field-select"
						v-model="form.customerPhone" border="none" />
				</up-form-item>
				<up-form-item label="付款方式" label-width="120" prop="customerPay" required :borderBottom="true">
					<up-radio-group v-model="form.customerPay" shape="square">
						<up-radio v-for="(item, index) in customerPayList" :key="index" :name="item" :label="item"
							activeColor="green"></up-radio>
					</up-radio-group>
				</up-form-item>
				<up-form-item label="付款账户" label-width="120" prop="customerAccount" required :borderBottom="true">
					<up-input placeholder="请输入客户付款账户" type="text" class="form-field-select"
						v-model="form.customerAccount" border="none" />
				</up-form-item>
				<up-form-item label="是否开票" label-width="120" prop="isInvoicing" required :borderBottom="true">
					<up-radio-group v-model="form.isInvoicing" shape="square" @change="radioChange">
						<up-radio :key="0" :name="1" label="是" :customStyle="{marginRight: '16px'}"
							activeColor="green" />
						<up-radio :key="1" :name="0" label="否" :customStyle="{marginRight: '16px'}"
							activeColor="green" />
					</up-radio-group>
				</up-form-item>
				<!-- #ifdef APP -->

				<!-- <up-form-item label="收货人地址" label-width="120" prop="pcaAddress" required :borderBottom="true"
					@tap="cityShow=true">
					<up-input placeholder="请选择省市区" type="text" class="form-field-select" v-model="form.pcaAddress"
						readonly border="none" />
				</up-form-item>				
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<!-- <up-form-item label="收货人地址" label-width="120" prop="pcaAddress" required :borderBottom="true">
					<up-input placeholder="请选择省市区" type="text" class="form-field-select" v-model="form.pcaAddress"
                      border="none" @click.native="cityShow=true" @focus='blur'/>
				</up-form-item>	  -->
				<!-- #endif -->
				<!-- <up-form-item label="收货人详细地址" label-width="120" prop="customerAddress" required :borderBottom="true">
					<up-input placeholder="请填写收货人详细地址" type="text" class="form-field-select"
						v-model="form.customerAddress" border="none" />
				</up-form-item> -->
				<!-- 地址列表部分 -->
				<u-divider text="收货地址管理" :dashed="true" lineColor="#ff0000" textColor="#2979ff"></u-divider>

				<!-- 显示已有地址 -->
				<view v-for="(address, index) in form.addressList" :key="index" class="address-item">
					<up-form-item :label="`地址${index + 1}`" label-width="120" :borderBottom="true">
						<view class="address-content">
							<view class="address-info">
								<text
									class="address-text">{{ address.province }}/{{ address.city }}/{{ address.district }}</text>
								<text class="address-detail">{{ address.detail }}</text>
								<view class="address-actions">
									<text v-if="address.isDefault === 1" class="default-tag">默认地址</text>
									<text class="action-btn" @click="editAddress(index)">编辑</text>
									<text class="action-btn" @click="deleteAddress(address,index)">删除</text>
									<text v-if="address.isDefault !== 1" class="action-btn"
										@click="setDefaultAddress(index)">设为默认</text>
								</view>
							</view>
						</view>
					</up-form-item>
				</view>

				<!-- 添加新地址按钮 -->
				<view class="add-address-btn" @click="addNewAddress">
					<up-icon name="plus" color="#2979ff" size="16"></up-icon>
					<text>添加收货地址</text>
				</view>

				<!-- 地址编辑弹窗 -->
				<u-popup :show="addressEditShow" mode="center" round="10" @close="addressEditShow = false">
					<view class="address-edit-popup">
						<view class="popup-header">
							<text>{{ editingAddressIndex === null ? '添加地址' : '编辑地址' }}</text>
							<up-icon name="close" @click="addressEditShow = false"></up-icon>
						</view>
						<view class="popup-content">
							<!-- #ifdef APP -->
							<up-form-item label="省市区" label-width="120" required :borderBottom="true"
								@tap="cityShow=true">
								<up-input placeholder="请选择省市区" type="text" class="form-field-select"
									v-model="editingAddress.pcaAddress" readonly border="none" />
							</up-form-item>
							<!-- #endif -->
							<!-- #ifdef H5 -->
							<up-form-item label="省市区" label-width="120" required :borderBottom="true">
								<up-input placeholder="请选择省市区" type="text" class="form-field-select"
									v-model="editingAddress.pcaAddress" border="none" @click.native="cityShow=true"
									@focus='blur' />
							</up-form-item>
							<!-- #endif -->
							<up-form-item label="详细地址" label-width="120" required :borderBottom="true">
								<up-input placeholder="请填写详细地址" type="text" class="form-field-select"
									v-model="editingAddress.detail" border="none" />
							</up-form-item>
							<up-form-item label="设为默认" label-width="120" :borderBottom="true">
								<up-switch v-model="editingAddress.isDefault" activeColor="green"></up-switch>
							</up-form-item>
						</view>
						<view class="popup-footer">
							<up-button type="default" @click="addressEditShow = false">取消</up-button>
							<up-button type="primary" @click="saveAddress">保存</up-button>
						</view>
					</view>
				</u-popup>

				<up-form-item label="是否签订合同" label-width="120" prop="isContracting" required :borderBottom="true">
					<up-radio-group v-model="form.isContracting" shape="square">
						<up-radio :key="0" :name="1" label="是" :customStyle="{marginRight: '16px'}"
							activeColor="green" />
						<up-radio :key="1" :name="0" label="否" :customStyle="{marginRight: '16px'}"
							activeColor="green" />
					</up-radio-group>
				</up-form-item>
				<up-form-item label="合同期限" label-width="120" prop="contractTime" :borderBottom="true"
					@tap="contractShow = true">
					<up-input placeholder="请选择合同期限" type="text" class="form-field-select" v-model="form.contractTime"
						border="none" readonly />
				</up-form-item>
				<up-form-item label="合同附件" label-width="120" :borderBottom="true">
					<up-input :placeholder="type==1?'请移至电脑端查看':'请移至电脑端上传'" type="text" class="form-field-select"
						border="none" readonly disabled />
				</up-form-item>
				<up-form-item label="营业执照" label-width="120" :borderBottom="true">
					<up-input :placeholder="type==1?'请移至电脑端查看':'请移至电脑端上传'" type="text" class="form-field-select"
						border="none" readonly disabled />
				</up-form-item>
				<up-form-item label="法人身份证" label-width="120" :borderBottom="true">
					<up-input :placeholder="type==1?'请移至电脑端查看':'请移至电脑端上传'" type="text" class="form-field-select"
						border="none" readonly disabled />
				</up-form-item>
				<up-form-item label="备注" label-width="120" :borderBottom="true">
					<up-input placeholder="备注" type="text" class="form-field-select" v-model="form.xustomerRemarks"
						border="none" />
				</up-form-item>
				<u-divider text="企业信息填写" :dashed="true" lineColor="#ff0000" textColor="#2979ff"></u-divider>
				<up-form-item label="企业名称" label-width="120" :borderBottom="true">
					<up-input placeholder="请输入企业名称" type="text" class="form-field-select" v-model="invoiceInfo.fullName"
						border="none" />
				</up-form-item>
				<up-form-item label="企业税号" label-width="120" :borderBottom="true">
					<up-input placeholder="请输入企业税号" type="text" class="form-field-select" v-model="invoiceInfo.duty"
						border="none" />
				</up-form-item>
				<up-form-item label="企业地址" label-width="120" :borderBottom="true">
					<up-input placeholder="请输入企业地址" type="text" class="form-field-select"
						v-model="invoiceInfo.fullAddress" border="none" />
				</up-form-item>
				<up-form-item label="联系电话" label-width="120" :borderBottom="true">
					<up-input placeholder="请输入联系电话" type="text" class="form-field-select"
						v-model="invoiceInfo.fullPhone" border="none" />
				</up-form-item>
				<up-form-item label="开户银行" label-width="120" :borderBottom="true">
					<up-input placeholder="请输入开户银行" type="text" class="form-field-select" v-model="invoiceInfo.bank"
						border="none" />
				</up-form-item>
				<up-form-item label="银行账户" label-width="120" :borderBottom="true">
					<up-input placeholder="请输入银行账户" type="text" class="form-field-select"
						v-model="invoiceInfo.bankAccount" border="none" />
				</up-form-item>
			</up-form>
		</view>

		<!-- 申请日期 -->
		<u-calendar :show="createDateShow" mode="single" @confirm="createDateChange" @close="createDateShow=false"
			:minDate="minDate" :maxDate="maxDate" :monthNum="12"></u-calendar>

		<!-- 省市区 -->
		<cityPicker :column="cityColumn" :default-value="cityDefaultValue" @cancel="cityCancel" @confirm="cityConfirm"
			:visible="cityShow" />

		<!-- 部门联动 -->
		<u-picker :show="departmentShow" :columns="departmentColumns" keyName="departmentName"
			@confirm="departmentConfirm" @close="departmentShow = false" @cancel="departmentShow = false"
			closeOnClickOverlay></u-picker>

		<!-- 销售人员联动 -->
		<u-picker :show="salePersonShow" :columns="salePersonList" keyName="realName" @confirm="salePersonConfirm"
			@close="salePersonShow = false" @cancel="salePersonShow = false" closeOnClickOverlay></u-picker>

		<!-- 客户形式联动 -->
		<u-picker :show="formShow" :columns="formList" keyName="customerForm" @confirm="formConfirm"
			@close="formShow = false" @cancel="formShow = false" closeOnClickOverlay></u-picker>

		<!-- 所在区域联动 -->
		<u-picker :show="areListShow" :columns="areList" keyName="regionName" @confirm="areListConfirm"
			@close="areListShow = false" @cancel="areListShow = false" closeOnClickOverlay></u-picker>

		<!-- 合同期限 -->
		<u-calendar :show="contractShow" mode="range" @confirm="contractConfirm" title="请选择合同期限" :minDate="minDate"
			:maxDate="maxDate" :monthNum="12" @close="contractShow=false"></u-calendar>


		<!-- 消息提示	 -->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import customerApi from '@/apis/gyl/customer.js';
	import baseApi from '@/apis/gyl/base.js';
	import departmentApi from '@/apis/gyl/department.js';
	import userApi from '@/apis/gyl/user.js';
	import cityPicker from '@/uni_modules/piaoyi-cityPicker/components/piaoyi-cityPicker/piaoyi-cityPicker';
	export default {
		components: {
			cityPicker,
		},
		data() {
			return {
				type: 0,
				addressEditShow: false,
				createDateShow: false,
				cityShow: false,
				cityDefaultValue: '',
				cityColumn: 3,
				minDate: '2024-12-01',
				maxDate: '2035-01-01',
				labelStyle: {
					color: '#646566',
					fontSize: '30rpx'
				},
				contractShow: false,
				// 地址编辑相关
				addressEditShow: false,
				editingAddressIndex: null,
				editingAddress: {
					addressId:null,
					customerId: null,
					province: '',
					city: '',
					district: '',
					detail: '',
					isDefault: 0,
					pcaAddress: ''
				},
				form: {
					accountPeriod: null,
					customerAccount: null,
					createDate: null,
					department: null,
					departmentId: null,
					salePerson: null,
					customerName: null,
					customerAddress: null,
					customerLevel: null,
					customerForm: null,
					customerTake: null,
					customerPhone: null,
					customerPay: null,
					isInvoicing: 0,
					isContracting: 0,
					textProvince: null,
					textCity: null,
					textArea: null,
					pcaAddress: null,
					contractTime: null,
					contractingStart: null,
					contractingEnd: null,
					xustomerRemarks: null,
					// 地址列表改为数组形式
					addressList: []
				},
				invoiceInfo: {
					fullName: null,
					duty: null,
					// address: null,
					// phone: null,
					fullAddress: null,
					fullPhone: null,
					bank: null,
					bankAccount: null
				},
				departmentShow: false,
				departmentColumns: [],
				salePersonShow: false,
				salePersonList: [],
				formShow: false,
				formList: [], //客户形式
				areListShow: false,
				areList: [],
				customerPayList: ['对公账户', '个人扫码', '转账'],
				accountPeriodList: ['发货前付款', '货到付款', '账期7天', '账期15天', '账期30天'],
				userRules: {
					accountPeriod: [{
						required: true,
						message: '请选择付款账期',
						trigger: ['blur', 'change']
					}],
					customerAccount: [{
						required: true,
						message: '请选择客户付款账户',
						trigger: ['blur', 'change']
					}],
					createDate: [{
						required: true,
						message: '请选择申请日期',
						trigger: ['blur', 'change']
					}],
					department: [{
						required: true,
						message: '请选择客户所在区域',
						trigger: ['blur', 'change']
					}],
					departmentName: [{
						required: true,
						message: '请选择部门',
						trigger: ['blur', 'change']
					}],
					salePerson: [{
						required: true,
						message: '请选择销售人员',
						trigger: ['blur', 'change']
					}],
					customerName: [{
						required: true,
						message: '请填写客户姓名',
						trigger: ['blur', 'change']
					}],
					// customerAddress: [{
					// 	required: true,
					// 	message: '请填写详细地址',
					// 	trigger: ['blur', 'change']
					// }],
					// customerLevel: [{
					// 	required: true,
					// 	message: '请填写客户等级',
					// 	trigger: ['blur', 'change']
					// }],
					customerForm: [{
						required: true,
						message: '请选择客户形式',
						trigger: ['blur', 'change']
					}],
					customerTake: [{
						required: true,
						message: '请选择收货人',
						trigger: ['blur', 'change']
					}],
					customerPhone: [{
						required: true,
						message: '请选择收货人电话',
						trigger: ['blur', 'change']
					}],
					customerPay: [{
						required: true,
						message: '请选择客户付款方式',
						trigger: ['blur', 'change']
					}],
					isInvoicing: [{
						type: 'integer',
						required: true,
						message: '请选择客户是否开票',
						trigger: ['blur', 'change']
					}],
					isContracting: [{
						type: 'integer',
						required: true,
						message: '请选择客户是否签订合同',
						trigger: ['blur', 'change']
					}],
				}
			}
		},
		async onNavigationBarButtonTap() {
			console.info(this.form)
			var flag = false;

			// 添加地址列表验证
			if (!this.form.addressList || this.form.addressList.length === 0) {
				uni.$u.toast('请至少添加一个收货地址');
				return;
			}
			await this.$refs.userForm.validate().then(res => {
				flag = true;
			}).catch(errors => {
				uni.$u.toast(errors[0].message)
			})
			if (flag) {
				this.form.invoiceInfo = this.invoiceInfo;

				// 确保地址列表中的每个地址都包含 customerId（编辑模式下）
				if (this.type == 1) {
					const customerId = this.form.customerId; // 确保这个字段存在
					if (customerId) {
						this.form.addressList.forEach(address => {
							address.customerId = customerId;
						});
					}
				}
				if (this.type == 1) {
					const res = await userApi.customerUpdate(this.form);
					if (res.success) {
						this.$refs.uToast.show({
							type: 'success',
							message: '客户更新成功',
							duration: 1500, // 设置适当的持续时间
							complete: () => {
								uni.navigateBack()
							}
						});
					} else {
						this.$refs.uToast.show({
							type: 'error',
							message: '客户更新失败',
							duration: 1500, // 设置适当的持续时间
							complete: () => {
								uni.navigateBack()
							}
						});
					}
				} else {
					const res = await userApi.customerAdd(this.form);
					if (res.success) {
						this.$refs.uToast.show({
							type: 'success',
							message: '客户添加成功',
							duration: 1500, // 设置适当的持续时间
							complete: () => {
								uni.navigateBack()
							}
						});
					} else {
						this.$refs.uToast.show({
							type: 'error',
							message: '客户添加失败',
							duration: 1500, // 设置适当的持续时间
							complete: () => {
								uni.navigateBack()
							}
						});
					}
				}

			}
		},
		onReady() {
			console.info(11111)
			this.$refs.userForm.setRules(this.userRules);
		},
		methods: {
			/**
			 * 禁止弹出
			 */
			async blur() {
				await uni.hideKeyboard();
			},
			radioChange(e) {
				console.info(1111)
				this.$refs.userForm.validateField('isInvoicing');
				this.$refs.userForm.validateField('isContracting');
			},
			// 地址管理相关方法
			/**
			 * 添加新地址
			 */
			addNewAddress() {
				this.editingAddressIndex = null;
				this.editingAddress = {
					province: '',
					city: '',
					district: '',
					detail: '',
					isDefault: this.form.addressList.length === 0, // 第一个地址默认设为默认地址
					pcaAddress: ''
				};
				this.addressEditShow = true;
			},

			/**
			 * 编辑地址
			 * @param {Number} index 地址索引
			 */
			editAddress(index) {
				const address = this.form.addressList[index];
				console.log('address', address)
				this.editingAddressIndex = index;
				this.editingAddress = {
					addressId: address.addressId,
					customerId: address.customerId,
					province: address.province,
					city: address.city,
					district: address.district,
					detail: address.detail,
					isDefault: address.isDefault === 1,
					pcaAddress: `${address.province}/${address.city}/${address.district}`
				};
				this.addressEditShow = true;
			},

			/**
			 * 删除地址
			 * @param {Object} address 地址对象
			 * @param {Number} index 地址索引
			 */
			deleteAddress(address, index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这个地址吗？',
					success: async (res) => {
						if (res.confirm) {
							// 如果是编辑模式且地址有addressId，调用API删除
							if (this.type == 1 && address.addressId) {
								try {
									const deleteRes = await customerApi.deleteCustomerAddress({
										addressId: address.addressId,
										customerId: address.customerId
									});

									if (deleteRes.success) {
										// 从本地列表中移除
										this.form.addressList.splice(index, 1);

										// 如果删除的是默认地址，设置第一个地址为默认
										if (address.isDefault === 1 && this.form.addressList.length > 0) {
											this.form.addressList[0].isDefault = 1;
										}

										uni.$u.toast('地址删除成功');
									} else {
										uni.$u.toast('地址删除失败');
									}
								} catch (error) {
									console.error('删除地址失败:', error);
									uni.$u.toast('删除地址时发生错误');
								}
							} else {
								// 新增模式或没有addressId，直接从本地列表移除
								this.form.addressList.splice(index, 1);

								// 如果删除的是默认地址，设置第一个地址为默认
								if (address.isDefault === 1 && this.form.addressList.length > 0) {
									this.form.addressList[0].isDefault = 1;
								}

								uni.$u.toast('地址删除成功');
							}
						}
					}
				});
			},
			/**
			 * 设为默认地址
			 * @param {Number} index 地址索引
			 */
			setDefaultAddress(index) {
				this.form.addressList.forEach((address, i) => {
					address.isDefault = i === index ? 1 : 0;
				});
			},
			/**
			 * 保存地址
			 */
			saveAddress() {
				if (!this.editingAddress.province || !this.editingAddress.detail) {
					uni.$u.toast('请完善地址信息');
					return;
				}

				const addressData = {
					addressId:this.editingAddress.addressId,
					customerId:this.editingAddress.customerId,
					province: this.editingAddress.province,
					city: this.editingAddress.city,
					district: this.editingAddress.district,
					detail: this.editingAddress.detail,
					isDefault: this.editingAddress.isDefault ? 1 : 0
				};

				if (this.editingAddressIndex === null) {
					// 新增地址
					if (addressData.isDefault) {
						// 如果设为默认，取消其他地址的默认状态
						this.form.addressList.forEach(addr => addr.isDefault = 0);
					}
					this.form.addressList.push(addressData);
				} else {
					// 编辑地址
					if (addressData.isDefault) {
						// 如果设为默认，取消其他地址的默认状态
						this.form.addressList.forEach(addr => addr.isDefault = 0);
					}
					this.form.addressList[this.editingAddressIndex] = addressData;
					
				}

				this.addressEditShow = false;
			},
			/**
			 * 申请日期
			 * @param {Object} e
			 */
			createDateChange(e) {
				this.form.createDate = e[0];
				this.createDateShow = false;
			},
			/**
			 * 部门确定
			 * @param {Object} e
			 */
			departmentConfirm(e) {
				console.info(e)
				this.form.departmentId = e.value[0].id; //获取选择的数据
				this.form.departmentName = e.value[0].departmentName; //获取选择的数据
				this.$refs.userForm.validateField('departmentName');
				this.departmentShow = false;
				this.handleQuery(e.value[0].id);
				this.form.salePerson = '';
			},

			/**
			 * 销售人员确定
			 * @param {Object} e
			 */
			salePersonConfirm(e) {
				this.form.salePerson = e.value[0].realName; //获取选择的数据
				this.$refs.userForm.validateField('salePerson');
				this.salePersonShow = false;

			},

			/**客户形式
			 * @param {Object} e
			 */
			formConfirm(e) {
				this.form.customerForm = e.value[0].customerForm; //获取选择的数据
				this.$refs.userForm.validateField('customerForm');
				this.formShow = false;
			},

			/**
			 * 所在区域确定
			 * @param {Object} e
			 */
			areListConfirm(e) {
				this.form.department = e.value[0].regionName; //获取选择的数据
				this.$refs.userForm.validateField('department');
				this.areListShow = false;
			},

			/**
			 * 省市区取消
			 */
			cityCancel() {
				this.cityShow = false;
			},

			/**省市区确认
			 * @param {Object} e
			 */
			cityConfirm(e) {
				// 更新编辑中的地址信息
				this.editingAddress.province = e.provinceName;
				this.editingAddress.city = e.cityName;
				this.editingAddress.district = e.areaName;
				this.editingAddress.pcaAddress = e.provinceName + "/" + e.cityName + "/" + e.areaName;

				// 保留原来的逻辑（如果需要的话）
				this.form.textProvince = e.provinceName;
				this.form.textCity = e.cityName;
				this.form.textArea = e.areaName;
				this.form.pcaAddress = e.provinceName + "/" + e.cityName + "/" + e.areaName;
				this.cityCancel();
			},

			/**合同期限
			 * @param {Object} e
			 */
			contractConfirm(e) {
				this.form.contractingStart = e[0];
				this.form.contractingEnd = e[1];
				this.contractShow = false;
				this.form.contractTime = e[0] + '至' + e[1];
			},
			// -----------------------------------------------------------------------------api----------------------------------------------------------------------------
			/**
			 * 获取部门数据
			 */
			async getDepartmentListApi() {
				const res = await departmentApi.listNoTree();
				this.departmentColumns = [];
				if (res.success) {
					const list = res.data;
					// const departmentColumns = list.map(item => item.departmentName);
					this.departmentColumns.push(list);
				}
			},

			/**销售人员
			 * @param {Object} id
			 */
			async handleQuery(id) {
				//发送查询请求
				const params = {
					departmentId: id,
					pageNo: 1,
					pageSize: 2000
				}
				let res = await userApi.getUserList(params);
				this.salePersonList = [];
				if (res.success) {
					this.salePersonList.push(res.data.records)
				}
			},

			/**
			 * 客户形式
			 */
			async getCustomerForm() {
				var data = {
					pageNo: 1,
					pageSize: 30,
				};
				let res = await userApi.getClientFormList(data);
				this.formList = [];
				if (res.success) {
					this.formList.push(res.data.records);
				}
			},

			/**
			 * 获取所在区域
			 */
			async getAreaListApi() {
				const res = await baseApi.listArea();
				this.areList = [];
				if (res.success) {
					this.areList.push(res.data)
				}
			},
		},
		onLoad(option) {
			this.getDepartmentListApi();
			this.handleQuery('');
			this.getCustomerForm();
			this.getAreaListApi();

			if (option.type) {
				uni.setNavigationBarTitle({
					title: "编辑客户"
				});
				this.type = 1;
				var data = uni.getStorageSync("customer");

				// 处理企业信息
				this.invoiceInfo.fullName = data.fullName;
				this.invoiceInfo.duty = data.duty;
				this.invoiceInfo.fullAddress = data.fullAddress;
				this.invoiceInfo.fullPhone = data.fullPhone;
				this.invoiceInfo.bank = data.bank;
				this.invoiceInfo.bankAccount = data.bankAccount;

				// 处理表单数据
				this.form = {
					...data,
					// 保留原来的地址字段用于兼容性
					textProvince: data.textProvince,
					textCity: data.textCity,
					textArea: data.textArea,
					// 使用addressList作为主要地址数据
					addressList: data.addressList || []
				};

				// 如果没有addressList，从旧字段创建默认地址
				if (!this.form.addressList || this.form.addressList.length === 0) {
					this.form.addressList = [{
						province: data.textProvince,
						city: data.textCity,
						district: data.textArea,
						detail: data.customerAddress,
						isDefault: 1
					}];
				}

				this.form.contractingStart = data.contractingStart;
				this.form.contractingEnd = data.contractingEnd;
				if (this.form.contractingStart) {
					this.form.contractTime = data.contractingStart + '至' + data.contractingEnd;
				}
			} else {
				// 新增客户时初始化一个空地址列表
				this.form.addressList = [];
			}
		}
	}
</script>

<style lang="scss" scoped>
	.apply-form-field {
		background: #ffffff;

		.u-form-item {
			padding: 0px 15px !important;
		}

		.input-placeholder {
			text-align: left !important;
			font-size: 28rpx;
		}

		.uni-input-input {
			text-align: left !important;
		}

		.form-field-select {
			.u-iconfont {
				font-size: 0 !important;
			}
		}

		.add-user {
			color: #bfbfbf;
			font-size: 30px;
		}

		.apply-name {
			color: #333333;
			line-height: 20px;

			span {
				color: #999999;
				display: block;

			}
		}

		.apply-link {
			.u-link {
				color: #5ab149 !important;
				padding: 0 5px;
			}
		}

		.u-close--top-right {
			top: 5px !important;
		}

		.popup-title {
			color: #333333;
			padding: 5px 10px;
			font-size: 30rpx;
		}

		.u-cell {
			padding: 8px 12px !important;
		}
	}

	.u-form {
		background-color: #fff;
		border-left: 2px solid #f0f0f1;
		border-top: 2px solid #f0f0f1;
		border-right: 1px solid #bcbcbd;
		border-bottom: 1px solid #bcbcbd;
		box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
		border-radius: 15px;
	}

	.u-radio-group--row {
		flex-wrap: wrap;
	}

	.u-radio {
		margin-right: 8px !important;
	}

	.u-radio-group {
		gap: 0px !important;
	}

	::v-deep .u-cell__value {
		text-align: left !important;
		width: 60% !important;
	}

	.address-item {
		margin-bottom: 10rpx;
		border: 1px solid #f0f0f0;
		border-radius: 8rpx;
		padding: 10rpx;
	}

	.address-content {
		width: 100%;
	}

	.address-info {
		display: flex;
		flex-direction: column;
	}

	.address-text {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 5rpx;
	}

	.address-detail {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 10rpx;
	}

	.address-actions {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.default-tag {
		background: #2979ff;
		color: white;
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
		font-size: 22rpx;
	}

	.action-btn {
		color: #2979ff;
		font-size: 24rpx;
	}

	.add-address-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
		border: 1px dashed #2979ff;
		border-radius: 8rpx;
		color: #2979ff;
		margin: 20rpx 0;
	}

	.address-edit-popup {
		width: 600rpx;
		background: white;
		border-radius: 16rpx;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1px solid #f0f0f0;
		font-weight: bold;
	}

	.popup-content {
		padding: 30rpx;
	}

	.popup-footer {
		display: flex;
		gap: 20rpx;
		padding: 30rpx;
		border-top: 1px solid #f0f0f0;
	}

	.popup-footer .up-button {
		flex: 1;
	}
</style>
